package com.shiro.app;

import com.bean.ResponseBean;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;


@Component
public class JwtUtil {
    //密码，绝对保密，写在配置文件中
    public static String sercetKey = "mingtianhenganghao";
    public  static long keeptime = 18000000;

    public static ResponseBean checkLogin(HttpServletRequest request)
    {

        String token = request.getHeader("token");
        if (token==null)
        {
        }
        String username = JwtUtil.getUsername(token);

        if (token == null || username == null) {
            return new ResponseBean(401, "没有登录", null);
        }

        return null;

    }

   /* @Value("${token.sercetKey}")
    public  static String sercetKey;
    @Value("${token.keeptime:30000}")
    public static long keeptime;*/

    public static void main(String[] args) {

        String token = JwtUtil.generToken("admin", null,null);
        System.out.println(token);
//
//        token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOssiJhZG1pbiIsImlhdCI6MTU3MzQzMjk4MCwiZXhwIjoxNTczNDM0NzgwfQ.B3935lyhGjOhDmK0ZfoamZQxWj1ib5EnEWybF3npefA";
//        String username = JwtUtil.getUsername(token);

//        String s = JwtUtil.generToken(null, "198", null);

        String stationId = JwtUtil.getStationId("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwiaWF0IjoxNTc3Mjc4NjI2LCJleHAiOjE1NzcyODA0MjZ9.nwjIXwlceYTcz95krSW8c4BXC_B9WclSsdPOb_3uuZU");

    }

    /**
     * 产生令牌
     * @param id  用户名
     * @param issuer  签发者
     * @param subject 主体（内容)
     * @return
     */
    public static String generToken(String id, String issuer, String subject) {
        long ttlMillis = keeptime;
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(sercetKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now);
        if (subject != null) {
            builder.setSubject(subject);
        }
        if (issuer != null) {
            builder.setIssuer(issuer);
        }
        builder.signWith(signatureAlgorithm, signingKey);

        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 更新令牌
     * @param token
     * @return
     */
    public static String updateToken(String token) {
        try {
            Claims claims = verifyToken(token);
            String id = claims.getId();
            String subject = claims.getSubject();
            String issuer = claims.getIssuer();
            Date date = claims.getExpiration();
            return generToken(id, issuer, subject);
        } catch (Exception ex) {
            //  ex.printStackTrace();
        }
        return "";
    }

    /**
     * 获取用户名
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(sercetKey))
                    .parseClaimsJws(token).getBody();
            return claims.getId();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取站点ID
     * @param token
     * @return
     */
    public static String getStationId(String token) {

        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(sercetKey))
                    .parseClaimsJws(token).getBody();
            return claims.getIssuer();
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return null;
    }


    public static Claims verifyToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(sercetKey))
                .parseClaimsJws(token).getBody();
        return claims;
    }


}